package com.culture.config.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.config.environment.Environment;
import org.springframework.cloud.config.environment.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.culture.config.component.PropertyWorker;
import com.culture.config.dao.entity.*;
import com.culture.config.dao.mapper.*;
import com.culture.config.service.ConfigService;

import lombok.extern.slf4j.Slf4j;
 

@Slf4j
@Service
public class ConfigServiceImpl implements ConfigService{
	@Resource
	private AppMapper appMapper;
	@Autowired
	private PropertyWorker propertyWorker;
	
	@Override
	public Environment findOne(String application, String profile, String label) {
		log.info("findOne:{},{},{}", application, profile, label);		
		if (StringUtils.isEmpty(application) || StringUtils.isEmpty(profile)) {
			return null;
		}
		App app = this.appMapper.getByName(application);
		if(Objects.isNull(app)) {
			log.info("find none:{},{},{}", application, profile, label);
			return new Environment(application,StringUtils.split(profile,",")); 
		}
		List<Property> propertyList = this.propertyWorker.getConfigProperties(app, profile, label);
		if(CollectionUtils.isEmpty(propertyList)) {
			log.info("find none:{},{},{}", application, profile, label);		
			return new Environment(application,StringUtils.split(profile,",")); 
		}
		Environment environment = new Environment(application, StringUtils.split(profile,","), label,"1.0.1", "LONGWUWEI");
		Map<String, String> configMap = propertyList.stream().collect(Collectors.toMap(Property::getPropertyKey, Property::getPropertyValue));		
		environment.add(new PropertySource(application + "_" + profile + "_" + label, configMap));	
		return environment;
	}
		
}
